package com.weijun.keepalive

import android.app.Application
import android.content.Context
import android.content.Intent
import android.os.Build
import android.util.Log
import com.weijun.keepalive.service.JobHandlerService

/**
 * @author: weijun
 * date: 2023/7/5
 * description:
 */
internal var keepAlive:KeepAlive ?= null

internal fun String.logE(){
    if (keepAlive?.debugger == true) {
        Log.e("KeepAlive",this)
    }
}

fun Application.keepAlive(block:KeepAlive.() -> Unit){
    block.invoke(KeepAlive().apply { application = this@keepAlive })
}

fun KeepAlive.notificationConfig(block:NotificationConfig.() -> Unit){
    block.invoke(notificationConfig)
}

fun KeepAlive.start(){
    if (application == null) {
        "Application 不能为 null".logE()
        return
    }
    keepAlive = this
    "当前配置信息：".logE()
    keepAlive!!.toString().logE()
    if (application?.isMainProcess() != true) {
        "不在主进程，跳过".logE()
        return
    }
    //启动定时器，在定时器中启动本地服务和守护进程
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        application?.startForegroundService(Intent(application, JobHandlerService::class.java))
    } else {
        application?.startService(Intent(application, JobHandlerService::class.java))
    }
}

class KeepAlive {

    var application: Application ?= null

    var debugger = false //是否打印日志
    var notificationConfig = NotificationConfig()
    var playMusic = false //是否播放无声音频
    var runMode = RunMode.ROGUE //是否流氓模式

    var onWorking:() -> Unit = {}
    var onStop:() -> Unit = {}

    override fun toString(): String {
        return "notificationConfig=$notificationConfig,debugger=$debugger,playMusic=$playMusic,runMode=$runMode"
    }
}

enum class RunMode {
    ENERGY, //省电模式，但保活效果会差一点
    ROGUE, //流氓模式，相对耗电，但可造就不死之身
}

data class NotificationConfig(
    var title:String = "",
    var description:String = "",
    var iconRes:Int = 0,
    var showFlag:Boolean = false //是否显示通知
) {
    var notificationClick:(Context, Intent) -> Unit = {_,_->}

    override fun toString(): String {
        return "title=$title,description=$description,showFlag=$showFlag"
    }
}